<!-- 接入日志 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset"/>
      <div class="tabclick">
        <div class="tabitem" @click="handleClick()">
          <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span><!-- 显示综合统计 -->
        </div>
      </div>
      <el-row>
        <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" @tab-click="tabClick">
          <el-tab-pane label="按日新增加趋势统计" lazy>
            <el-col :xs="24" :sm="24" :lg="24">
              <barchart :chartData="barchartData" @barclick="barclick"/>
            </el-col>
          </el-tab-pane>
          <el-tab-pane label="服务器使用时间统计" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart :title="'服务器使用时间统计'" :chartData="pieData" @pieclick="pieclick"/>
              </el-col>
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="终端使用时间统计" lazy>
            <el-row :gutter="20">
              <el-col :xs="24" :sm="24" :lg="24">
                <piechart :title="'终端使用时间统计'" :chartData="pieData2" @pieclick="pieclick"/>
              </el-col>
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-row>
      <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }" style="padding-right: 8px;margin:16px 0;">
        <el-table stripe border :data="tableData" style="width: 100%; margin-top: 15px">
          <el-table-column label="序号"  width="60" type="index" :index='(index)=>{return (index + 1) + (this.pageNum - 1)*this.pageSize}'> </el-table-column>
          <el-table-column label="服务器名称" prop="ServerName" width="160px" align="left"></el-table-column>
          <el-table-column label="终端用户" prop="EmployeeName" width="160px" align="left"></el-table-column>
          <el-table-column label="开始时间" prop="StartTime" align="left"></el-table-column>
          <el-table-column label="结束时间" prop="EndTime" align="left"></el-table-column>
          <el-table-column label="使用时长" prop="usageDuration" align="left"></el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart2.vue";
import piechart from "./components/piechart.vue";
import { formatDuration, parseTime } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js"
export default {
  components: { connsearch, barchart, piechart },
  data() {
    let that = this
    return {
      timer: null,
      activeName: "",
      tabTitle: '按日新增加趋势统计',
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      barchartData: {xAxis:[],series:[]},
      pieData: [],
      pieData2: [],
      tableData:[],
      searchform:{},
      searchobj: {},
      formOptions: [
        {
          col: 8,
          hidden: false,
          label: "日期", // label文字
          prop: "timeRange", // 字段名
          initValue: [], // 字段初始值,
          element: "el-date-picker", // 指定elementui组件
          type: "", // 日期选择类型,
          events: {
            input(val) {
              that.searchform.timeRange = val
            },
          },
        },
        {
          col: 8,
          hidden: false,
          label: "服务器", // label文字
          prop: "URL", // 字段名
          element: "el-select", // 指定elementui组件
          initValue: '', // 字段初始值,
          placeholder: "请选择服务器", // elementui组件属性
          options: [],
          rules: [], // elementui组件属性
          events: {
            input(val) {
              that.searchform.URL = val
            },
          },
        },
        {
          col: 8,
          label: "操作用户",
          prop:"Name",
          element: "el-cascader",
          initValue: "",
          placeholder: "请选择操作用户",
          options:[],
          checkStrictly: false,
          events: {
            input(val) {
              that.searchform.Name = val
            },
          },
        },
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    let xTime = new Date().getTime()
    let endTime = new Date(new Date().setHours(0, 0, 0, 0))
    let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
    // let arr = [ parseTime(startTime), parseTime(xTime)]
    let arr = [ parseTime(startTime),'']
    this.formOptions.map( item => {
      if(item.label === '日期'){
        item.initValue = arr
      }
    })
    this.$set(this.searchform,'timeRange', arr)
    // this.GetDepartment()
    this.GetAmazonCfg()
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  beforeDestroy() {
    this.timer = null
  },
  methods: {
    // 获取所有数据
    getData(){
      this.GetAmazonLog()
      switch (this.tabTitle) {
        case '按日新增加趋势统计':
          this.GetAmazonLogSumGroupByDate()
          break;
        case '终端使用时间统计':
          this.GetAmazonLogSumGroupByName()
          break;
        default:
          this.GetAmazonLogSumGroupByServer()
          break;
      }
    },
    async GetAmazonCfg(){
      const res = await connrequest('GetAmazonCfg')
      let arr = []
      res.Data.map(item => {
        arr.push({label: item.Name, value: item.Name})
      })
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "服务器"){
          item.options = arr
        }
        return item
      })
    },
    tabClick(row){
      this.tabTitle = row.label
      switch (this.tabTitle) {
        case '按日新增加趋势统计':
          this.GetAmazonLogSumGroupByDate()
          break;
        case '终端使用时间统计':
          this.GetAmazonLogSumGroupByName()
          break;
        default:
          this.GetAmazonLogSumGroupByServer()
          break;
      }
    },
    barclick(val){
      this.pageNum = 1
      this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
      this.GetAmazonLog(this.searchobj)
    },
    pieclick(val,title){
      this.pageNum = 1
      if(title === '服务器使用时间统计'){
        this.searchobj = { }
        this.GetAmazonLog(this.searchobj)
      }else if(title === '终端使用时间统计'){
        this.searchobj = { Name: val }
        this.GetAmazonLog(this.searchobj)
      }
    },
    // 获取部门和终端用户
    async GetDepartment(){
      const departments = await connrequest('GetDepartment')
      const employees = await connrequest('GetEmployee')
      departments.Data.map(item => {
        item.SubClass = item.DepartmentName
      })
      employees.Data.map(item => {
        item.SubClass = item.Name
        item.ParentID = item.DID
      })
      this.getnewarr(departments.Data, employees.Data)
    },
    getnewarr(departments, employees){
      const newDepartmentArray = [];
      //遍历departments数组
      departments.forEach(department => {
          //新建一个对象，用于存储合并后的数据
          const newDepartmentObj = {
              DepartmentName: department.DepartmentName,
              SubClass: department.DepartmentName,
              ParentName: department.ParentName,
              ID: department.ID,
              ParentID: department.ParentID,
              children: []
          };
          //遍历employees数组
          employees.forEach(employee => {
              //如果employee的Department和department的DepartmentName相同
              if (employee.Department === department.DepartmentName) {
                  //将该employee对象添加到newDepartmentObj的children数组中
                  newDepartmentObj.children.push(employee);
              }
          });
          //将newDepartmentObj添加到newDepartmentArray数组中
          newDepartmentArray.push(newDepartmentObj);
      });
      const convertedArray = this.convertArray(newDepartmentArray);
      this.formOptions.map( item => {
        if(item.label === '操作用户'){
          item.options = convertedArray
        }
      })
    },
    convertArray(data) {
      const map = {};
      const result = [];
      data.forEach(item => {
        if(!item.children){
          item.children = [];
        }
        map[item.ID] = item;
      });
      data.forEach(item => {
        if (item.ParentID !== 0) {
          const parent = map[item.ParentID];
          parent.children.push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    // 获取操作日志列表
    async GetAmazonLog(searchobj = {}){
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          SumCount: this.searchform.Account || '',
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : '',
          URL: this.searchform.URL || '',
          ...searchobj
        }
      }
      const res = await connrequest('GetAmazonLog', data)
        res.Data = res.Data || []
        res.Data = res.Data.map(item => {
          item.usageDuration = formatDuration( item.EndTime - item.StartTime )
          item.StartTime = parseTime(item.StartTime)
          item.EndTime = parseTime(item.EndTime)
          return item
        })
        this.tableData = res.Data
        this.total = res.Paging.TotalCount
    },
    // 按日统计
    async GetAmazonLogSumGroupByDate(){
      let xAxis = []
      let series= []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : '',
          URL: this.searchform.URL || '',
          SumCount: this.searchform.Account || '',
        }
      }
      const res = await connrequest('GetAmazonLogSumGroupByDate', data)
        res.Data = res.Data || []
        res.Data.map( item =>{
          xAxis.push(item.Name)
          series.push(item.Count)
        })
        this.barchartData = {xAxis,series}
    },
    // 服务器使用时间统计
    async GetAmazonLogSumGroupByServer(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : '',
          URL: this.searchform.URL || '',
          SumCount: 10,
        }
      }
      const res = await connrequest('GetAmazonLogSumGroupByServer', data)
        res.Data = res.Data || []
        res.Data.map( item =>{
          arr.push({name: item.Name, value: item.Count})
        })
        this.pieData = arr
    },
    // 终端使用时间统计
    async GetAmazonLogSumGroupByName(){
      let arr = []
      const data = {
        Filter:{
          StartTime: this.searchform.timeRange?.[0] ||  '',
          EndTime: this.searchform.timeRange?.[1] || '',
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : '',
          URL: this.searchform.URL || '',
          SumCount: 10,
        }
      }
      const res = await connrequest('GetAmazonLogSumGroupByName', data)
        res.Data = res.Data || []
        res.Data.map( item =>{
          arr.push({name: item.Name, value: item.Count})
        })
        this.pieData2 = arr
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = {}
      this.searchform = val
      if(this.searchform.timeRange){
        this.searchobj = { StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData()
    },
    // 重置
    reset(){
      this.pageNum = 1
      let xTime = new Date().getTime()
      let endTime = new Date(new Date().setHours(0, 0, 0, 0))
      let startTime = endTime - (Cookies.get('DefaultLogDays') * 1 * 3600 * 24 * 1000);
      // let arr = [ parseTime(startTime), parseTime(xTime)]
      let arr = [ parseTime(startTime),'']
      this.formOptions = this.formOptions.map( item => {
        if(item.label === "日期"){
          item.initValue = arr
        }else if(item.label === "统计排名"){
          item.initValue = 10
        }else{
          item.initValue = ""
        }
        return item
      })
      this.searchform = {}
      this.$set(this.searchform,'timeRange', arr)
      this.$refs.connsearch.addInitValue()
      this.getData()
    },
    handleSizeChange(pageSize){
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetAmazonLog(this.searchobj)
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.GetAmazonLog(this.searchobj)
    },
    handleClick() {
      this.tab = !this.tab
    },
  },
};
</script>
<style lang="scss" scoped>
@import "./components/css/conncss.scss";
</style>